<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2021/8/5
 * Time: 13:56
 */

namespace app\api\controller;


use think\Db;

class My extends Base
{
    private $user_id;
    private $create_time;
    private $page;
    
    /**
     * 异地登录验证
     * @return string
     */
    public function __construct()
    {
        $this->user_id = input('user_id');
        $this->page = input('page') ? input('page') : 1;
        $this->create_time = date('Y-m-d H:i:s');
    }
    
    /**
     * 个人信息
     * @return \think\response\Json
     */
    public function userInfo(){
        $user = Db::table('up_u_user')
            ->where('user_id', $this->user_id)
//            ->field('user_phone, user_username, user_image, user_is_real_name, user_card_code, user_real_name')
            ->find();
        // 未读消息数量
        $unread = $this->getNotice(2);
        $user['unread_number'] = count($unread);
        return json(['status' => 200, 'msg' => $user]);
    }
    
    /**
     * 更新用户信息
     * @return \think\response\Json
     * user_username    用户昵称
     * user_image       头像
     */
    public function updateUser(){
        $user_username = input('user_username');
        $user_image = input('user_image');
        
        $update['user_id'] = $this->user_id;
        if(isset($user_username)) $update['user_username'] = $user_username;
        if(isset($user_image)) $update['user_image'] = $user_image;
        
        $res = Db::table('up_u_user')->update($update);
        if($res){
            return json(['status' => 200, 'msg' => '编辑成功']);
        }else{
            return json(['status' => 0, 'msg' => '编辑失败']);
        }
    }
    
    // ================================  设置  start  ======================== //
    /**
     * 实名认证
     * @return \think\response\Json
     * user_card_code     身份证号
     * user_real_name     真实姓名
     * phone              手机号
     * code               验证码
     */
    public function realNameAuth(){
        $user_card_code = trim(input('user_card_code'));
        $user_real_name = trim(input('user_real_name'));
        $phone = trim(input('phone'));
        $code = trim(input('code'));
        
        if($user_card_code == '') return json(['status' => 0, 'msg' => '请输入身份证号']);
        if($user_real_name == '') return json(['status' => 0, 'msg' => '请输入真实姓名']);
        if($phone == '') return json(['status' => 0, 'msg' => '请输入手机号']);
        if($code == '') return json(['status' => 0, 'msg' => '请输入验证码']);
        if(!preg_match("/^1[3456789]\d{9}$/", $phone)) {
            return json(['status' => 0, 'msg' => '请输入正确格式的手机号']);
        }
        
        //=========验证验证码
        $res = Db::table('up_phonecode')
            ->where('phone', $phone)
            ->order('time desc')
            ->limit(1)
            ->find();
        if($code != $res['code']) {
            return json(['status' => 0, 'msg' => '验证码错误']);
        }
        // 10分钟超时
        $now = time();
        if($now - $res['time'] >= 601) {
            return json(['status' => 0, 'msg' => '验证码超时']);
        }
        if($res['status'] == 1) {
            return json(['status' => 0, 'msg' => '验证码已使用']);
        }
        
        $update =[
            'user_is_real_name' => 2,
            'user_card_code' => $user_card_code,
            'user_real_name' => $user_real_name,
            'user_real_name_time' => $this->create_time
        ];
        $result = Db::table('up_u_user')->where('user_id', $this->user_id)->update($update);
        if($result){
            //修改验证码状态
            Db::table('up_phonecode')->where('id', $res['id'])->setField('status', 1);
            return json(['status' => 200, 'msg' => '提交成功']);
        }else{
            return json(['status' => 0, 'msg' => '提交失败']);
        }
    }
    
    /**
     * 更换手机号---第一步
     * @return \think\response\Json
     * phone     手机号
     * code      验证码
     */
    public function updatePhoneF(){
        $phone = trim(input('phone'));
        $code = trim(input('code'));
        
        if($phone == '') return json(['status' => 0, 'msg' => '请输入手机号']);
        if($code == '') return json(['status' => 0, 'msg' => '请输入验证码']);
        if(!preg_match("/^1[3456789]\d{9}$/", $phone)) {
            return json(['status' => 0, 'msg' => '请输入正确格式的手机号']);
        }
    
        //=========验证验证码
        $res = Db::table('up_phonecode')
            ->where('phone', $phone)
            ->order('time desc')
            ->limit(1)
            ->find();
        if($code != $res['code']) {
            return json(['status' => 0, 'msg' => '验证码错误']);
        }
        // 10分钟超时
        $now = time();
        if($now - $res['time'] >= 601) {
            return json(['status' => 0, 'msg' => '验证码超时']);
        }
        if($res['status'] == 1) {
            return json(['status' => 0, 'msg' => '验证码已使用']);
        }
        //修改验证码状态
        $result = Db::table('up_phonecode')->where('id', $res['id'])->setField('status', 1);
        if($result){
            return json(['status' => 200, 'msg' => '验证成功，前往绑定新手机号']);
        }else{
            return json(['status' => 0, 'msg' => '验证失败']);
        }
    }
    
    /**
     * 更换手机号第二步
     * @return \think\response\Json
     * phone     手机号
     * code      验证码
     */
    public function updatePhoneS(){
        $phone = trim(input('phone'));
        $code = trim(input('code'));
    
        if($phone == '') return json(['status' => 0, 'msg' => '请输入手机号']);
        if($code == '') return json(['status' => 0, 'msg' => '请输入验证码']);
        if(!preg_match("/^1[3456789]\d{9}$/", $phone)) {
            return json(['status' => 0, 'msg' => '请输入正确格式的手机号']);
        }
        
        $user = Db::table('up_u_user')->where('user_phone', $phone)->find();
        if($user) return json(['status' => 0, 'msg' => '该手机号已绑定其它账号']);
    
        //=========验证验证码
        $res = Db::table('up_phonecode')
            ->where('phone', $phone)
            ->order('time desc')
            ->limit(1)
            ->find();
        if($code != $res['code']) {
            return json(['status' => 0, 'msg' => '验证码错误']);
        }
        // 10分钟超时
        $now = time();
        if($now - $res['time'] >= 601) {
            return json(['status' => 0, 'msg' => '验证码超时']);
        }
        if($res['status'] == 1) {
            return json(['status' => 0, 'msg' => '验证码已使用']);
        }
    
        $result = Db::table('up_u_user')->where('user_id', $this->user_id)->update(['user_phone' => $phone]);
        if($result){
            //修改验证码状态
            Db::table('up_phonecode')->where('id', $res['id'])->setField('status', 1);
//            $userInfo = Db::table('up_u_user')->where('user_phone', $phone)->find();
            return json(['status' => 200, 'msg' => '更新成功']);
        }else{
            return json(['status' => 0, 'msg' => '系统异常，绑定失败']);
        }
    }
    // ================================  设置  end  ======================== //
    
    // ================================  银行卡  start  ======================== //
    /**
     * 银行卡类型列表
     * @return \think\response\Json
     */
    public function bankList(){
        $bank = Db::table('up_bankcard_type')
            ->where('bt_status', 1)
            ->field('bt_id, bt_name, bt_card_type')
            ->select();
        return json(['status' => 200, 'msg' => $bank]);
    }
    
    /**
     * 我的银行卡列表
     * @return \think\response\Json
     */
    public function bankCardList(){
        $card = Db::table('up_user_bank')
            ->join('up_bankcard_type', 'bt_id = ub_bt_id', 'LEFT')
            ->field('ub_id, ub_bankcard_code, bt_name, bt_logo, bt_card_type')
            ->where('ub_user_id', $this->user_id)
            ->order('bt_time desc')
            ->select();
        if($card){
            return json(['status' => 200, 'msg' => $card]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 添加银行卡
     * @return \think\response\Json
     * bt_id    银行卡类型ID
     * bankcard_code    银行卡号
     * bankcard_code_auth    确认银行卡
     */
    public function addBankCard(){
        $bt_id = input('bt_id');
        $ub_bankcard_code = trim(input('bankcard_code'));
        $bankcard_code_auth = trim(input('bankcard_code_auth'));
        
        if(!$ub_bankcard_code) return json(['status' => 0, 'msg' => '请输入银行卡号']);
        if(!$bankcard_code_auth) return json(['status' => 0, 'msg' => '请确认银行卡号']);
        if($ub_bankcard_code != $bankcard_code_auth) return json(['status' => 0, 'msg' => '两次输入的银行卡号不一致']);
        
        $insert = [
            'ub_user_id' => $this->user_id,
            'ub_bankcard_code' => $ub_bankcard_code,
            'ub_bt_id' => $bt_id,
            'up_time' => $this->create_time
        ];
        $res = Db::table('up_user_bank')->insert($insert);
        if($res){
            return json(['status' => 200, 'msg' => '添加成功']);
        }else{
            return json(['status' => 0, 'msg' => '添加失败']);
        }
    }
    
    /**
     * 解绑银行卡
     * @return \think\response\Json
     * ub_id      我的银行卡ID
     */
    public function delBankCard(){
        $ub_id = input('ub_id');
        $res = Db::table('up_user_bank')->delete($ub_id);
        if($res){
            return json(['status' => 200, 'msg' => '删除成功']);
        }else{
            return json(['status' => 0, 'msg' => '删除失败']);
        }
    }
    // ================================  银行卡  end  ======================== //
    
    // ================================  地址管理  start  ======================== //
    /**
     * 添加地址
     * @return \think\response\Json
     * addr_name        姓名
     * addr_phone       电话
     * addr_sheng       省
     * addr_shi         市
     * addr_qu          区
     * addr_address     详细地址
     * addr_is_default  是否默认    1 默认   2 非默认
     */
    public function addAddress(){
        $addr_name = trim(input('addr_name'));
        $addr_phone = trim(input('addr_phone'));
        $addr_sheng = input('addr_sheng');
        $addr_shi = input('addr_shi');
        $addr_qu = input('addr_qu');
        $addr_address = input('addr_address');
        $addr_is_default = input('addr_is_default'); // 是否默认   1 默认    2 非默认
        
        if(!$addr_name || !$addr_phone || !$addr_sheng || !$addr_shi || !$addr_qu || !$addr_address){
            return json(['status' => 0, 'msg' => '请完善信息']);
        }
        
        $insert = [
            'addr_user_id' => $this->user_id,
            'addr_name' => $addr_name,
            'addr_phone' => $addr_phone,
            'addr_sheng' => $addr_sheng,
            'addr_shi' => $addr_shi,
            'addr_qu' => $addr_qu,
            'addr_address' => $addr_address,
            'addr_time' => $this->create_time
        ];
        // 是否是第一条
        $is_first = Db::table('up_user_address')
            ->where(['addr_status' => 1, 'addr_user_id' => $this->user_id])
            ->find();
        if(!$is_first){
            $addr_is_default = 1;
        }else{
            // 是否是默认
            if($addr_is_default == 1){
                Db::table('up_user_address')
                    ->where(['addr_status' => 1, 'addr_user_id' => $this->user_id, 'addr_is_default' => 1])
                    ->setField('addr_is_default', 2);
            }
        }
        $insert['addr_is_default'] = $addr_is_default;
        $res = Db::table('up_user_address')->insert($insert);
        if($res){
            return json(['status' => 200, 'msg' => '添加成功']);
        }else{
            return json(['status' => 0, 'msg' => '添加失败']);
        }
    }
    
    /**
     * 我的地址列表
     * @return \think\response\Json
     */
    public function addrList(){
        $list = Db::table('up_user_address')
            ->join('up_area a1', 'addr_sheng = a1.district_id', 'LEFT')
            ->join('up_area a2', 'addr_shi = a2.district_id', 'LEFT')
            ->join('up_area a3', 'addr_qu = a3.district_id', 'LEFT')
            ->where(['addr_status' => 1, 'addr_user_id' => $this->user_id])
            ->field('addr_id, addr_name, addr_phone, a1.district sheng, a2.district shi, a3.district qu, 
            addr_address, addr_is_default')
            ->order('addr_is_default asc, addr_time desc')
            ->select();
        if($list){
            return json(['status' => 200, 'msg' => $list]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 地址详情
     * @return \think\response\Json
     * addr_id      地址ID
     */
    public function addrDetail(){
        $addr_id = input('addr_id');
        $addr = Db::table('up_user_address')
            ->where('addr_id', $addr_id)
            ->field('addr_id, addr_name, addr_phone, addr_sheng, addr_shi, addr_qu, addr_address, addr_is_default')
            ->find();
        $province = Db::table('up_area')->where('level', 1)->field('district_id, district')->select();
        $city = Db::table('up_area')->where('pid', $addr['addr_sheng'])->field('district_id, district')->select();
        $district = Db::table('up_area')->where('pid', $addr['addr_shi'])->field('district_id, district')->select();
        return json(['status' => 200, 'msg' => $addr, 'province' => $province, 'city' => $city, 'district' => $district]);
    }
    
    /**
     * 编辑地址
     * @return \think\response\Json
     * addr_id       地址ID
     * addr_name     姓名
     * addr_phone    电话
     * addr_sheng    省ID
     * addr_shi      市ID
     * addr_qu       区ID
     * addr_address  详细地址
     * addr_is_default   是否默认   1 默认   2 非默认
     */
    public function editAddr(){
        $addr_id = input('addr_id');
        $addr_name = trim(input('addr_name'));
        $addr_phone = trim(input('addr_phone'));
        $addr_sheng = input('addr_sheng');
        $addr_shi = input('addr_shi');
        $addr_qu = input('addr_qu');
        $addr_address = input('addr_address');
        $addr_is_default = input('addr_is_default'); // 是否默认   1 默认    2 非默认
    
        if(!$addr_name || !$addr_phone || !$addr_sheng || !$addr_shi || !$addr_qu || !$addr_address){
            return json(['status' => 0, 'msg' => '请完善信息']);
        }
        
        $addr = Db::table('up_user_address')->where('addr_id', $addr_id)->field('addr_is_default')->find();
        if($addr['addr_is_default'] == 1){
            if($addr_is_default == 2) return json(['status' => 0, 'msg' => '此地址为默认地址，请先设置其它地址为默认地址']);
        }else{
            if($addr_is_default == 1){
                Db::table('up_user_address')
                    ->where(['addr_status' => 1, 'addr_user_id' => $this->user_id, 'addr_is_default' => 1])
                    ->setField('addr_is_default', 2);
            }
        }
        $update = [
            'addr_id' => $addr_id,
            'addr_name' => $addr_name,
            'addr_phone' => $addr_phone,
            'addr_sheng' => $addr_sheng,
            'addr_shi' => $addr_shi,
            'addr_qu' => $addr_qu,
            'addr_address' => $addr_address,
            'addr_is_default' => $addr_is_default,
            'addr_update_time' => $this->create_time
        ];
        $res = Db::table('up_user_address')->update($update);
        if($res){
            return json(['status' => 200, 'msg' => '编辑成功']);
        }else{
            return json(['status' => 0, 'msg' => '编辑失败']);
        }
    }
    
    /**
     * 删除地址
     * @return \think\response\Json
     * addr_id     地址ID
     */
    public function delAddr(){
        $addr_id = input('addr_id');
        $addr = Db::table('up_user_address')->where('addr_id', $addr_id)->field('addr_is_default')->find();
        if($addr['addr_is_default'] == 1) return json(['status' => 0, 'msg' => '请先设置其它地址为默认地址']);
        $res = Db::table('up_user_address')->where('addr_id', $addr_id)->setField('addr_status', 2);
        if($res){
            return json(['status' => 200, 'msg' => '删除成功']);
        }else{
            return json(['status' => 0, 'msg' => '删除失败']);
        }
    }
    
    // ================================  地址管理  end  ======================== //
    
    // ================================  我的顾问  start  ======================== //
    /**
     * 我的顾问
     * @return \think\response\Json
     * shi_id     定位市ID
     */
    public function myCounselor(){
        $shi_id = input('shi_id');
        $counselor = Db::table('up_counselor')
            ->where('counselor_shi', $shi_id)
            ->where('counselor_status', 1)
            ->field('counselor_work_year, counselor_wx, counselor_phone, counselor_image, counselor_star')
            ->find();
        if($counselor){
            return json(['status' => 200, 'msg' => $counselor]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    // ================================  我的顾问  end  ======================== //
    
    // ================================  常见问题  start  ======================== //
    /**
     * 常见问题
     * @return \think\response\Json
     */
    public function problem(){
        $list = Db::table('up_problem')
            ->field('problem_id, problem_title, problem_content')
            ->order('problem_time desc')
            ->select();
        if($list){
            return json(['status' => 200, 'msg' => $list]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    // ================================  常见问题  end  ======================== //
    
    // ================================  消息  start  ======================== //
    /**
     * 消息列表
     * @return \think\response\Json
     * page     页码
     */
    public function noticeList(){
        $list = $this->getNotice();
        if($list){
            foreach($list as $k => $v){
                if(strpos($v['notice_read_user'], ',' . $this->user_id . ',') !== false){
                    $is_read = 1; // 已读
                }else{
                    $is_read = 2; // 未读
                }
                $list[$k]['is_read'] = $is_read;
            }
            return json(['status' => 200, 'msg' => $list]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 消息详情
     * @return \think\response\Json
     * notice_id      消息ID
     */
    public function noticeDetail(){
        $notice_id = input('notice_id');
        $notice = Db::table('up_notice')
            ->where('notice_id', $notice_id)
            ->field('notice_read_user, notice_content, notice_title, notice_time')
            ->find();
        // 标记已读
        if(strpos($notice['notice_read_user'], ',' . $this->user_id . ',') === false){
            $read_user = $notice['notice_read_user'] . $this->user_id . ',';
            Db::table('up_notice')->where('notice_id', $notice_id)->update(['notice_read_user' => $read_user]);
        }
        return json(['status' => 200, 'msg' => $notice]);
    }
    
    /**
     * 删除消息
     * @return \think\response\Json
     * del_range     1 全部删除    2 批量删除
     * notice_ids    被批量删除的消息ID，逗号隔开
     */
    public function delNotice(){
        $del_range = input('del_range'); // 1 全部  2 批量
        $notice_ids = input('notice_ids'); // 被批量删除的消息ID
        
        if($del_range == 1){
            $notice = $this->getNotice(1, 2);
        }else{
            $notice = Db::table('up_notice')->where('notice_id', 'IN', $notice_ids)
                ->field('notice_id, notice_del_user')
                ->select();
        }
        if($notice){
            Db::startTrans();
            try{
                foreach($notice as $k => $v){
                    $del_user = $v['notice_del_user'] . $this->user_id . ',';
                    Db::table('up_notice')->where('notice_id', $v['notice_id'])->setField('notice_del_user', $del_user);
                }
                Db::commit();
                return json(['status' => 200, 'msg' => '删除成功']);
            }catch(\Exception $e){
                Db::rollback();
                return json(['status' => 0, 'msg' => $e->getLine() . ':' . $e->getMessage()]);
            }
        }else{
            return json(['status' => 200, 'msg' => '没有可以删除的消息']);
        }
    }
    
    /**
     * 标记已读
     * @return \think\response\Json
     * read_range    1  全部标记   2 批量标记
     * notice_ids    被批量标记的消息ID，逗号隔开
     */
    public function readNotice(){
        $read_range = input('read_range'); // 1 全部  2 批量
        $notice_ids = input('notice_ids'); // 被批量标记已读的消息ID
        
        if($read_range == 1){
            $notice = $this->getNotice(2);
        }else{
            $notice = Db::table('up_notice')->where('notice_id', 'IN', $notice_ids)
                ->field('notice_id, notice_read_user')
                ->select();
        }
        if($notice){
            Db::startTrans();
            try{
                foreach($notice as $k => $v){
                    if(strpos($v['notice_read_user'], ',' . $this->user_id . ',') === false){
                        $read_user = $v['notice_read_user'] . $this->user_id . ',';
                        Db::table('up_notice')->where('notice_id', $v['notice_id'])->setField('notice_read_user', $read_user);
                    }
                }
                Db::commit();
                return json(['status' => 200, 'msg' => '标记成功']);
            }catch(\Exception $e){
                Db::rollback();
                return json(['status' => 0, 'msg' => $e->getMessage()]);
            }
        }else{
            return json(['status' => 200, 'msg' => true]);
        }
    }
    // ================================  消息  end  ======================== //
    
    
    
    
    
    // ****************************    公共方法
    /**
     * 获取消息数据
     * @param int $type    1 列表    2 未读消息数量
     * @param int $is_page    1 分页   2 不分页
     * @return false|int|\PDOStatement|string|\think\Collection
     */
    private function getNotice($type = 1, $is_page = 1){
        $where['notice_user'] = [['like', '%,' . $this->user_id . ',%'], ['=', -1], 'or'];
        $where['notice_del_user'] = ['notlike', '%' . $this->user_id . '%'];
        if($type == 2){ // 未读消息
            $where['notice_read_user'] = ['notlike', '%' . $this->user_id . '%'];
        }
        $query = Db::table('up_notice')->where($where);
        if($type == 1){
            $query->field('notice_id, notice_title, notice_content, notice_type, notice_time, notice_del_user, 
                notice_read_user')
                ->order('notice_time desc');
            if($is_page == 1){
                $data = $query->page($this->page, 20)->select();
            }else{
                $data = $query->select();
            }
        }else{
            $data = $query->field('notice_id, notice_read_user')->select();
        }
        return $data;
    }
}